<template>
  <div>
    <el-card shadow="never" class="margin-30">
      <div slot="header">
        <span>{{ articleId?'编辑文章':'新增文章' }}</span>
      </div>
      <el-form ref="form" :model="article" :rules="rules" label-width="120px" size="mini">
        <el-row :gutter="20">
          <el-col :span="6" :offset="0">
            <el-form-item label="作者" prop="author">
              <el-input v-model="article.author" placeholder="作者" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="标题" prop="title">
              <el-input v-model="article.title" placeholder="标题" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="是否展示">
              <!-- isShow (integer, optional): 是否显示: 0 否; 1 是 , -->
              <el-switch v-model="article.isShow" :active-value="1" :inactive-value="0" />

            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="13" :offset="0">
            <el-form-item label="摘要">
              <el-input
                v-model="article.summary"
                type="textarea"
                :rows="3"
                placeholder="请输入摘要"
              />
            </el-form-item>

          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="6" :offset="0">
            <el-form-item label="封面图片">
              <el-upload
                ref="upload"
                :action="uploadFileOss"
                :on-success="coverImgUploadSucc"
                :before-upload="beforeCoverImgUpload"
                :headers="token"
              >
                <el-button v-if="!article.coverImg" slot="trigger" size="small" type="primary">点击上传素材</el-button>
                <img v-else width="100" height="100" :src="article.coverImg" alt="">
                <div slot="tip" class="el-upload__tip">jpg/png/gif/webp/jpeg 文件大小不能超过1.5M</div>
              </el-upload>

            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="切换富文本类型" size="mini">
              <!-- editorType (integer, optional): 编辑器类型: 0 富文本; 1 markdown , -->
              <el-radio v-model="article.editorType" label="0" @change="clearContent">富文本</el-radio>
              <el-radio v-model="article.editorType" label="1" @change="clearContent">markdown</el-radio>
              <span style="color:#e6a23c;"> <i class="el-icon-warning" /> 注意!切换编辑器会清空编辑内容</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <div v-show="article.editorType==0"><Tinymce ref="tinymce" v-model="article.content1" /></div>
            <div v-show="article.editorType==1"> <mavon-editor ref="mavonEditor" v-model="article.content1" @imgAdd="$imgAdd" /></div>

          </el-col>

        </el-row>

        <el-form-item>
          <el-button type="primary" @click="doAddOrUpdateArticle">{{ articleId?"立即修改":"立即添加" }}</el-button>

        </el-form-item>
      </el-form>

    </el-card>

  </div>
</template>
<script>
import Tinymce from '@/components/Tinymce'

import mix from '@/mixins/index'
import axios from 'axios'
// https://www.npmjs.com/package/mavon-editor
import {
  addArticle as addArticleApi,
  productArticle as productArticleApi,
  updateArticle as updateArticleApi
} from '@/api/content/article'
export default {
  name: 'Detail',
  components: {
    Tinymce
  },
  mixins: [mix],
  data() {
    return {
      articleId: '',
      article: {
        editorType: '0',
        content1: '',
        isShow: 1,
        coverImg: ''
      },
      rules: {
        author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
      }
    }
  },

  watch: {
  },
  created() {
    this.articleId = this.$route.params.id
    if (this.articleId) { // 编辑文章
      this.getArticleDetail()
    }
  },
  mounted() {

  },
  methods: {
    async getArticleDetail() {
      const res = await productArticleApi(this.articleId)
      const { success, data, message } = res
      if (success) {
        const articleDetial = data.productArticle
        articleDetial.editorType = String(articleDetial.editorType)
        this.article = articleDetial
      } else {
        this.$message.error(message)
      }
    },
    // 绑定@imgAdd event
    $imgAdd(pos, $file) {
      var _this = this
      // 第一步.将图片上传到服务器.
      var formdata = new FormData()
      formdata.append('file', $file)
      axios({
        // url: 'http://leju.bufan.cloud/lejuAdmin/material/uploadFileOss',
        url: _this.uploadFileOss,
        method: 'post',
        data: formdata,
        headers: _this.token
      }).then((res) => {
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        /**
               * $vm 指为mavonEditor实例，可以通过如下两种方式获取
               * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
               * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
               */
        const { success, data, message } = res.data
        if (success) {
          this.$refs.mavonEditor.$img2Url(pos, data.fileUrl)
        } else {
          this.$message.error(message)
        }
      })
        .catch(err => {
          console.log(err)
        })
    },
    // 添加或更新文章
    doAddOrUpdateArticle() {
      this.$refs.form.validate(async(validate) => {
        if (validate) {
          // 校验成功
          //
          if (Number(this.article.editorType) === 0) {
            this.article.content2 = this.article.content1
          } else {
            this.article.content2 = this.$refs.mavonEditor.d_render
            // console.log(this.$refs.mavonEditor.d_render)
          }

          // console.log(this.article)
          let api = null
          if (this.articleId) { // 更新文章
            api = updateArticleApi
          } else { // 添加文章
            api = addArticleApi
          }
          const res = await api(this.article)
          const { success, message } = res
          if (success) {
            this.$router.push({ name: 'Article' })
          } else {
            this.$message.error(message)
          }
        } else {
          // 校验失败
          this.$message.error('注意表单校验！！！')
        }
      })
    },
    // 切换富文本，清除内容
    clearContent() {
      // console.log('123')

      if (Number(this.article.editorType) === 0) {
        this.$refs.tinymce.setContent('')
      } else {
        this.article.content1 = ''
      }
    },
    beforeCoverImgUpload(file) {
      // const isJPG = file.type === 'image/jpeg' || file.type === 'image/webp' || file.type === 'image/png' || file.type === 'image/gif'
      const reg = /^image\/(jpeg|png|jpg|gif|webp)$/
      const isRequiredImgForamt = reg.test(file.type)
      const isLt1dot5M = file.size / 1024 / 1024 < 1.5

      if (!isRequiredImgForamt) {
        this.$message.error('上传封面图片只能是 jpeg|png|jpg|gif 格式!')
      }
      if (!isLt1dot5M) {
        this.$message.error('上传封面图片大小不能超过 1.5MB!')
      }
      return isRequiredImgForamt && isLt1dot5M
    },
    coverImgUploadSucc(res) {
      // console.log('res==>', res)
      // console.log('file==>', file)
      // console.log('filelist==>', filelist)
      const { success, data, message } = res
      if (success) {
        this.article.coverImg = data.fileUrl
        // 清空列表
        this.$refs.upload.clearFiles()
      } else {
        this.$message.error(message)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
